package com.xuanyuan.qrscan

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.PointF
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.ContextCompat
import com.dlazaro66.qrcodereaderview.QRCodeReaderView
import com.xuanyuan.qrscan.databinding.ActivityQrscanBinding

private const val RC_CAMERA_PERMISSION = 1001

class QrscanActivity : AppCompatActivity(), QRCodeReaderView.OnQRCodeReadListener {
    private val EXTRA_ANIMATION_ARGS = "animation_args"

    private val binding: ActivityQrscanBinding by viewBindingFactory()
    private val vibrator by lazy { getSystemService(Context.VIBRATOR_SERVICE) as Vibrator }
    private var hasReadQrCode = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.qrView.setQRDecodingEnabled(true)
        binding.qrView.setAutofocusInterval(2000L)
        binding.qrView.setBackCamera()
        binding.qrView.setOnQRCodeReadListener(this)
        binding.qrView.setOnClickListener { binding.qrView.forceAutoFocus() }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!hasPermission(Manifest.permission.CAMERA)) {
                @Suppress("DEPRECATION")
                requestPermissions(arrayOf(Manifest.permission.CAMERA), RC_CAMERA_PERMISSION)
            }
        }
    }


    override fun onResume() {
        super.onResume()
        binding.qrView.startCamera()
        hasReadQrCode = false
    }

    override fun onPause() {
        super.onPause()
        binding.qrView.stopCamera()
    }

    override fun onQRCodeRead(url: String, pointFS: Array<PointF>) {
        if (hasReadQrCode) return
        hasReadQrCode = true
        vibrator.vibrateCompat(100)

        startActivity(intent(this, url))
    }


    private fun intent(context: Context, args: String): Intent {
        return Intent(context, ContentActivity::class.java).apply {
            putExtra(EXTRA_ANIMATION_ARGS, args)
        }
    }

    private fun Vibrator.vibrateCompat(millis: Long) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrate(VibrationEffect.createOneShot(millis, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            @Suppress("DEPRECATION")
            vibrate(millis)
        }
    }

    private fun Context.hasPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            permission
        ) == PackageManager.PERMISSION_GRANTED
    }
}